package com.bijiawang.search.dao;

import com.bijiawang.search.pojo.Goods;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class Srot {

    public static ArrayList<Goods> QuickSort(ArrayList<Goods> array, int start, int end) {
        if (array.size() < 1 || start < 0 || end >= array.size() || start > end) return null;
        int smallIndex = partition(array, start, end);
        if (smallIndex > start)
            QuickSort(array, start, smallIndex - 1);
        if (smallIndex < end)
            QuickSort(array, smallIndex + 1, end);
        return array;
    }

    public static int partition(ArrayList<Goods> array, int start, int end) {
        int pivot = (int) (start + Math.random() * (end - start + 1));
        if (array.get(pivot).getPrice().substring(1).equals("")){
            pivot = pivot + 1;
        }
        int smallIndex = start - 1;
        swap(array, pivot, end);
        for (int i = start; i <= end; i++)
            if (Float.parseFloat(array.get(i).getPrice().substring(1)) <= Float.parseFloat(array.get(end).getPrice().substring(1)) && !array.get(i).getPrice().equals("") ) {
                smallIndex++;
                if (i > smallIndex)
                    swap(array, i, smallIndex);
            }
        return smallIndex;
    }


    public static void swap(ArrayList<Goods> array, int i, int j) {
        Goods goodsI = array.get(i);
        array.set(i, array.get(j));
        array.set(j,goodsI);
    }

    public static int bottom(ArrayList<Goods> array, int start, int end){
        int pivot = (int) (start + Math.random() * (end - start + 1));
        if (array.get(pivot).getPrice().substring(1).equals("")){
            pivot = pivot + 1;
        }
        int smallIndex = start - 1;
        swap(array, pivot, end);
        for (int i = start; i <= end; i++)
            if (Float.parseFloat(array.get(i).getPrice().substring(1)) >= Float.parseFloat(array.get(end).getPrice().substring(1))) {
                smallIndex++;
                if (i > smallIndex)
                    swap(array, i, smallIndex);
            }
        return smallIndex;
    }

    public static ArrayList<Goods> buttomSort(ArrayList<Goods> array, int start, int end) {
        if (array.size() < 1 || start < 0 || end >= array.size() || start > end) return null;
        int smallIndex = bottom(array, start, end);
        if (smallIndex > start)
            buttomSort(array, start, smallIndex - 1);
        if (smallIndex < end)
            buttomSort(array, smallIndex + 1, end);
        return array;
    }

}
